package com.heima.wemedia.auto;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

public class Base64Utils {

    /**
     * 将图片文件或网络图片URL转换为Base64编码字符串
     *
     * @param imagePath 图片文件路径或网络图片URL
     * @return Base64编码字符串
     * @throws IOException 如果读取图片失败或不符合要求
     */
    public static String encodeImageToBase64(String imagePath) throws IOException {
        byte[] imageBytes = readImageBytes(imagePath);
        validateImageSize(imageBytes);
        BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(imageBytes));
        validateImageDimensions(bufferedImage);

        return Base64.getEncoder().encodeToString(imageBytes);
    }

    /**
     * 读取图片字节数据，支持本地文件路径和网络图片URL
     *
     * @param imagePath 图片路径或URL
     * @return 图片字节数组
     * @throws IOException 如果读取失败
     */
    private static byte[] readImageBytes(String imagePath) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try (InputStream inputStream = isHttpUrl(imagePath) ? openHttpStream(imagePath) : new FileInputStream(imagePath)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
        }
        return byteArrayOutputStream.toByteArray();
    }

    /**
     * 检查是否是HTTP/HTTPS链接
     *
     * @param path 路径字符串
     * @return 是否是HTTP/HTTPS链接
     */
    private static boolean isHttpUrl(String path) {
        return path.startsWith("http://") || path.startsWith("https://");
    }

    /**
     * 打开网络图片流
     *
     * @param imageUrl 网络图片URL
     * @return 输入流
     * @throws IOException 如果连接失败
     */
    private static InputStream openHttpStream(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        return connection.getInputStream();
    }

    /**
     * 验证图片大小是否在5KB到4MB之间
     *
     * @param imageBytes 图片字节数组
     * @throws IOException 如果超出范围
     */
    private static void validateImageSize(byte[] imageBytes) throws IOException {
        long sizeInKB = imageBytes.length / 1024;
        if (sizeInKB < 5 || sizeInKB > 4096) {
            throw new IOException("图片大小必须大于等于5KB且小于等于4MB");
        }
    }

    /**
     * 验证图片尺寸是否在128x128到4096x4096之间
     *
     * @param bufferedImage 图像对象
     * @throws IOException 如果尺寸不符合要求
     */
    private static void validateImageDimensions(BufferedImage bufferedImage) throws IOException {
        if (bufferedImage == null) {
            throw new IOException("不支持的图片格式");
        }
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();
        int minSide = Math.min(width, height);
        int maxSide = Math.max(width, height);
        if (minSide < 128 || maxSide > 4096) {
            throw new IOException("图片最短边必须大于等于128像素，最长边小于等于4096像素");
        }
    }
}
